package org.springcloud.plugin.config.center.initializer;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springcloud.plugin.common.entity.RuleEntity;
import org.springcloud.plugin.config.center.adpater.ConfigAdapter;
import org.springcloud.plugin.config.center.parser.CoreConfigParser;
import org.springcloud.plugin.framework.adapter.CoreAdapter;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.PostConstruct;

/**
 * author: yanggld
 * date: 2019/12/15 20:48
 * version: 1.0
 * description:
 * 应用启动时获取配置
 */
@Slf4j
public class ConfigInitializer {

    @Autowired(required = false)
    private ConfigAdapter configAdapter;

    @Autowired
    private CoreAdapter coreAdapter;

    @Autowired
    private CoreConfigParser coreConfigParser;

    @PostConstruct
    public void initialize() {
        log.info("***************配置初始化***************");
        log.info("***********************获取远程配置信息***************");
        String remoteConfig = getRemoteConfig();
        log.info(remoteConfig);
    }

    private String getRemoteConfig() {
        if (configAdapter != null) {
            String config = null;
            try {
                config = configAdapter.getConfig();
                if (StringUtils.isNotEmpty(config)) {
                    RuleEntity ruleEntity = coreConfigParser.parse(config);
                    coreAdapter.setRule(ruleEntity);
                }
            } catch (Exception e) {
                log.warn("Get remote config failed", e);
            }
            if (StringUtils.isNotEmpty(config)) {
                return config;
            }
        } else {
            log.info("Remote config loader isn't provided");
        }
        return null;
    }
}
